package cn.com.xy.sms.sdk.service.number;

import java.util.Map;

import org.json.JSONObject;

import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.util.CallBackState;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;
import cn.com.xy.sms.util.EmbedNumberUtils;
import cn.com.xy.sms.util.SdkCallBack;

/* IMOO-9 likuangkuang 20161014 start */
public class UpgradeNumberService {
	private static final String KEY_UPGRADE_DATA_TYPE = "dataType";
	private static final String KEY_UPGRADE_DATA_VERSION = "dataVersion";
	private static final int UPGRADE_DATA_TYPE_EMBED = 1;

	public static void queryByService(Map<String, String> queryMap, Map<String, String> extend,
			final XyCallBack callBack) {
		if (queryMap == null || queryMap.isEmpty()) {
			XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, "no version");
			return;
		}

		final String reqeustContent = createReqeustContent(queryMap, extend);
		if (StringUtils.isNull(reqeustContent)) {
			XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, "reqeustContent null");
			return;
		}

		SdkCallBack netSdkCallBack = new SdkCallBack() {

			@Override
			public void execute(Object... obj) {
				try {
					int callBackState = (Integer) obj[0];
					Object result = obj[1];
					if (callBackState != CallBackState.REQUEST_SUCCESS) {
						XyUtil.doXycallBackResult(callBack, callBackState, null, result);
						return;
					}

					JSONObject resultJson = new JSONObject((String) result);
					if (resultJson.length() > 0) {
						XyUtil.doXycallBackResult(callBack, CallBackState.HAS_DATA, resultJson);
					} else {
						XyUtil.doXycallBackResult(callBack, CallBackState.NO_DATA, "no data");
					}
				} catch (Throwable e) {
					LogManager.e(Constant.TAG, "UpgradeNumberService queryByService execute error:", e);
					XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, e.getMessage());
				}
			}
		};

		try {
			NetUtil.executeServiceHttpRequest(NetUtil.REQ_QUERY_UPGRADE, reqeustContent, extend, netSdkCallBack);
		} catch (Throwable e) {
			LogManager.e(Constant.TAG, "UpgradeNumberService queryByService error:", e);
			XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, e.getMessage());
		}
	}

	private static String createReqeustContent(Map<String, String> queryMap, Map<String, String> extend) {
		if (queryMap == null || queryMap.isEmpty()) {
			return null;
		}

		try {
			JSONObject reqeustContent = new JSONObject();
			reqeustContent.put(KEY_UPGRADE_DATA_TYPE, UPGRADE_DATA_TYPE_EMBED);
			reqeustContent.put(KEY_UPGRADE_DATA_VERSION, queryMap.get(EmbedNumberUtils.KEY_DATA_QUERY_VERSION));
			return reqeustContent.toString();
		} catch (Throwable e) {
			LogManager.e(Constant.TAG, "UpgradeNumberService createReqeustContent error:", e);
		}

		return null;
	}
}
/* IMOO-9 likuangkuang 20161014 end */
